<!--白名单-->
<template>
  <div class="white-list">
    <div class="title">白名单</div>
    <el-form :inline="true" class="search-form">
      <el-form-item label="订单号">
        <el-input v-model="orderNo" placeholder="请输入订单号" clearable />
      </el-form-item>
      <el-form-item label="产品类型" style="width: 360px;">
        <a-cascader
          v-model="categoryValue"
          :options="categoryList"
          placeholder="请选择产品类型"
          clearable
          @change="handleCategory">
        </a-cascader>
      </el-form-item>
      <el-form-item label="产品名称">
        <el-select v-model="productValue" filterable placeholder="请选择产品名称" clearable>
          <el-option
            v-for="item in productOptions"
            :key="item.productId"
            :label="item.productName"
            :value="item.productId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-button class="btn" type="primary" size="14" @click="queryList()">查询</el-button>
    </el-form>
    <div class="header">
      <div class="num-title">总数量：{{ totalAmount }}，已使用：{{ usageAmount }}</div>
      <el-button type="primary" class="button-container" size="14" @click="handleAddOrder">新增订单</el-button>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      size="medium"
      :header-cell-style="{ background: '#F5F6F7' }"
    >
      <el-table-column label="订单号">
        <template slot-scope="scope">
          {{ scope.row.orderNo || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="订单说明">
        <template slot-scope="scope">
          {{ scope.row.orderDescription || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="白名单数量">
        <template slot-scope="scope">
          {{ scope.row.totalAmount || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="已使用数量">
        <template slot-scope="scope">
          {{ scope.row.usageAmount || "-" }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="operate" @click="jumpDetails(scope.row)">详情</el-button>
          <el-button
            type="text"
            size="operate"
            :disabled="scope.row.usageAmount !== '0'"
            @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page="currentPage"
      :page-sizes="[10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>
    <el-dialog
      title="新增订单"
      :visible.sync="dialogVisible"
      width="596px"
      :before-close="handleClose"
      custom-class="white-list-dialog">
      <el-form
        ref="form"
        :model="addFormData"
        :rules="rules"
        width="596px"
        label-width="80px"
        label-position="right">
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="addFormData.orderNo" placeholder="请输入订单号" maxlength="30" clearable></el-input>
        </el-form-item>
        <el-form-item label="产品信息" prop="productId">
          <el-input v-model="addFormData.productId" placeholder="请输入产品PID" clearable></el-input>
        </el-form-item>
        <el-form-item label="订单说明" prop="orderDescription">
          <el-input
            v-model="addFormData.orderDescription"
            placeholder="请输入订单说明，最多100个字符"
            type="textarea"
            maxlength="100"
            show-word-limit
            :rows="6"
            clearable>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="14" @click="handleClose">取 消</el-button>
        <el-button type="primary" size="14" @click="onsubmit">确 定 </el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { deviceCategories } from '@/api/product/create-product'
import { getList, addWhiteList, statistics, deleteWhiteList, product } from '@/api/device-identity-auth/white-list'
// 按需引入 Cascader 组件
import { Cascader } from 'ant-design-vue'
export default {
  name: 'whiteList',
  components: {
    'a-cascader': Cascader
  },
  data() {
    return {
      tableData: [], // 列表数据
      totalAmount: '', // 三元组总数
      usageAmount: '', // 三元组已使用数
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页条数
      total: 0, // 列表数据总条数
      loading: true,
      orderNo: '', // 订单号
      categoryValue: '', // 级联筛选大品类列表
      categoryFilterValue: '', // 接口传参产品大类+小类拼接
      categoryList: [], // 品类列表
      productOptions: [], // 产品筛选列表
      productValue: '',
      addFormData: {
        orderNo: '', // 订单号
        productId: '', // 产品信息
        orderDescription: '' // 订单说明
      },
      rules: {
        orderNo: [
          { required: true, message: '请输入订单号', trigger: 'blur' },
          { min: 1, max: 30, message: '请输入规范的订单号', trigger: 'blur' },
          { validator: this.validateOrderNo, trigger: 'blur' }
        ],
        productId: [
          { required: true, message: '请输入产品信息', trigger: 'blur' }
        ],
        orderDescription: [
          { required: true, message: '请输入订单说明', trigger: 'blur' },
          { min: 1, max: 100, message: '请输入规范的订单说明', trigger: 'blur' }
        ]
      },
      dialogVisible: false
    }
  },
  created() {
    this.queryCategory()
    this.queryProduct()
    this.queryList()
    this.queryStatistics()
  },
  methods: {
    /**
     * 查询列表
     */
    queryList(condition) {
      this.loading = true
      const params = {
        orderNo: this.orderNo,
        categoryInfoId: this.categoryFilterValue,
        productId: this.productValue,
        size: this.pageSize,
        current: this.currentPage
      }
      getList(params).then(res => {
        this.tableData = res.data.data.records
        this.total = res.data.data.total
      }).catch(err => {
        this.$message.error(err.message)
      }).finally(() => {
        this.loading = false
      })
    },
    // 白名单数据统计
    queryStatistics() {
      statistics().then(res => {
        this.totalAmount = res.data.data.totalAmount
        this.usageAmount = res.data.data.usageAmount
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 新增订单
    handleAddOrder() {
      this.dialogVisible = true
    },
    // 跳转详情
    jumpDetails(row) {
      this.$router.push({
        path: '/device-identity-auth/white-list/details',
        query: {
          id: row.id
        }
      })
    },
    // 删除
    handleDelete(id) {
      const params = {
        id: id
      }
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteWhiteList(params).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.queryList()
          this.queryStatistics()
        }).catch(err => {
          this.$message.error(err.message)
        })
      }).catch(err => {})
    },
    // 查询产品品类
    queryCategory() {
      deviceCategories().then(res => {
        this.rawData = res.data.data.categories
        this.categoryList = this.rawData.map(std => ({
          label: std.standardCategory,
          value: std.standardCategory,
          children: std.primaryClassification.map(primary => ({
            label: primary.category,
            value: primary.category,
            children: primary.secondClassification.map(second => ({
              label: second.name,
              value: second.categoryCode
            }))
          }))
        }))
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 查询产品
    queryProduct() {
      const params = {
        category: '',
        categoryCode: this.categoryFilterValue
      }
      product(params).then(res => {
        this.productOptions = res.data.data
        // const newObject = {
        //   productId: "ALL",
        //   productName: "所有产品"
        // }
        // this.productOptions.unshift(newObject)
        // this.queryList('search')
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 选择品类
    handleCategory(value) {
      this.categoryFilterValue = value[value.length - 1]
      this.productValue = ''
      this.queryProduct()
    },
    // 关闭新增订单弹窗
    handleClose() {
      this.dialogVisible = false
      this.$refs['form'].resetFields()
    },
    /**
     * 新增订单
     */
    onsubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = {
            ...this.addFormData
          }
          addWhiteList(params).then(res => {
            this.$message({
              type: 'success',
              message: '新增成功!'
            })
            this.queryList()
            this.queryStatistics()
          }).catch(err => {
            this.$message.error(err.message)
          }).finally(() => {
            this.dialogVisible = false
            this.$refs['form'].resetFields()
          })
        } else {
          return false
        }
      })
    },
    // 每页条数改变时触发
    handleSizeChange(val) {
      this.pageSize = val
      this.queryList()
    },
    // 当前页变时触发
    handleCurrentChange(val) {
      this.currentPage = val
      this.queryList()
    }
  }
}
</script>
<style lang="scss" scoped>
.white-list {
  .title {
      font-size: 18px;
      font-weight: 400;
      color: #252525;
    }
  .search-form {
    margin: 20px 0 10px 0;

    .btn {
      float: right;
    }
  }

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    .num-title {
      background: rgba(39, 95, 232, 0.1);
      padding: 10px;
      color: #252525;
      font-size: 18px;
    }
  }
  ::v-deep .ant-cascader-picker:focus .ant-cascader-input,
  ::v-deep .ant-input:focus,
  ::v-deep .ant-input:focus {
    border-color: #275FE8;
  }
}
</style>
<style>
.ant-cascader-menu-item:hover {
  background: #F5F7FA;
}
</style>
